<?php
namespace app\home\controller;
header("Content-type: text/html; charset=utf-8");
use app\admin\model\Student;
use app\admin\model\Teacher;
use app\admin\model\Order;
use think\Cache;
use think\Controller;
use think\Db;
use think\Validate;
use app\admin\model\User;
use think\Log;
class Login extends Controller {

    /**
     * 会员登录
     * @param username string 用户名 *必传
     * @param password string 密码 *必传
     * @author 王柯 <wangke.email@foxmail.com>
     * @return array|string|\think\response\Json
     */
    public function index(){
        $data = $_POST;
        if(empty($data)) {
            return show(config('code.error'), '数据不合法！', [], 404);
        }

        if(!isset($data['username'])){
            return show(config('code.error'), 'username is not find', [], 404);
        }

        if(!isset($data['password'])){
            return show(config('code.error'), 'password is not find', [], 404);
        }

        try{
            $data['password'] = md5($data['password']);
            $user = Db::name('user')
                ->where('username="' . $data['username'] . '" OR tel="' . $data['username'] . '"')
                ->find();
            if(!empty($user)){
                if($data['password'] != $user['password']){
                    return show(config('code.error'),'密码错误！');
                }else{
                    if($user['user_auth']==3){
                        return show(config('code.success'),'学生登录成功',$user);
                    }else if($user['user_auth']==2){
                        return show(config('code.success'),'教师登录成功',$user);
                    }else{
                        return show(config('code.success'),'非教师用户登录',$user);
                    }
                }
            }else{
                return show(config('code.error'),'登录失败，用户名不存在');
            }
        }catch (\Exception $e){
            Log::write($e->getMessage());
            return show(config('code.error'),'内部错误，登录失败！',[],500);
        }
    }

    /**
     * 手机号登陆
     * @param tel int 用户手机号 *必传
     * @author 王柯 <wangke.email@foxmail.com>
     * @return array|string|\think\response\Json
     */
    public function tel_login(){
        $data = $_POST;
        if(empty($data)) {
            return show(config('code.error'), '数据不合法！', [], 404);
        }

        if(!isset($data['tel'])){
            return show(config('code.error'), 'tel is not find', [], 404);
        }

        try{
            $user = Db::name('user')
                ->where('tel='.$data['tel'])
                ->find();
            if(!empty($user)){
                if($user['user_auth']==3){
                    return show(config('code.success'),'学生登录成功',$user);
                }else if($user['user_auth']==2){
                    return show(config('code.success'),'教师登录成功',$user);
                }else{
                    return show(config('code.success'),'非教师用户登录',$user);
                }
            }else{
                return show(config('code.error'),'登录失败，用户名不存在');

            }
        }catch (\Exception $e){
            Log::write($e->getMessage());
            return show(config('code.error'),'内部错误，请求失败！',[],400);
        }

    }

    /**
     * 学生信息获取
     * @param id int 学生id *必传
     * @author 王柯 <wangke.email@foxmail.com>
     * @return array|string|\think\response\Json
     */
    public function student(){
        $data = $_POST;
        if(empty($data)) {
            return show(config('code.error'), '数据不合法！', [], 404);
        }

        if(!isset($data['id'])){
            return show(config('code.error'), 'id is not find', [], 404);
        }

        try{
            $students = Db::name('student');
            $student = $students
                ->join('book_user','student_id=book_user.id','LEFT')
                ->join('book_grade','grade_id=book_grade.id','LEFT')
                ->join('book_city','city_id=book_city.id','LEFT')
                ->join('book_student_rank','student_rank_id=book_student_rank.id','LEFT')
                ->where(array('student_id'=>$data['id']))
                ->find();
            return show(config('code.success'),'获取学生信息成功！',$student);
        }catch (\Exception $e){
            Log::write($e->getMessage());
            return show(config('code.error'),'内部错误，请求失败！',[],400);
        }
    }

    /**
     * 教师信息获取
     * @param id int 学生id *必传
     * @author 王柯 <wangke.email@foxmail.com>
     * @return array|string|\think\response\Json
     */
    public function teacher(){
        $data = $_POST;
        if(empty($data)) {
            return show(config('code.error'), '数据不合法！', [], 404);
        }

        if(!isset($data['id'])){
            return show(config('code.error'), 'id is not find', [], 404);
        }

        try{
            $teachers = Db::name('teacher');
            $teacher = $teachers
                ->join('book_user','teacher_id=book_user.id','LEFT')
                ->join('book_city','city_id=book_city.id','LEFT')
                ->join('book_teacher_rank','teacher_rank_id=book_teacher_rank.id','LEFT')
                ->where(array('teacher_id'=>$data['id']))
                ->find();
            return show(config('code.success'),'获取教师信息成功！',$teacher);
        }catch (\Exception $e){
            Log::write($e->getMessage());
            return show(config('code.error'),'内部错误，请求失败！',[],400);
        }
    }

    //发送短信
    public function sendMsg(){
        //实例化
        $sms = new \ali_message\SendMessage(
            "LTAI28yOwo9Y3Pgh",
            "LZ34WauMGGCAm4Un56s5dd9rwixCHI"
        );
//发送短信
        $Phone = $_POST['tel'];
        $code=rand(1000 ,9999);
        $date = date('Ymd');
        if($Phone){
           $res=  $sms->sendSms(
                  "好书换好课", // 短信签名
                  "SMS_80190250", // 短信模板编号
                  $Phone, // 短信接收者
                  Array(  // 短信模板中字段的值
                      "code"=>$code,
                  )
            );
           $res =$sms->queryDetails(
                 $Phone,  // phoneNumbers 电话号码
                  $date, // sendDate 发送时间
                  10, // pageSize 分页大小
                  1 // currentPage 当前页码
              );
           echo json_encode($code);
        }



    }

    //新增会员
    public function add_member(){
        if(request()->isPost()){
            $_POST['ctime'] = time();
            $_POST['password']=md5($_POST['password']);
            $users = new User();
            $info = $users->where(array('tel'=>$_POST['tel']))->find();
            if(empty($info)){
                if ($id = $users->insertGetId($_POST)) {
                    if(input('post.user_auth') == 2){
                        $teacher = Db::name('teacher');
                        $data['teacher_id'] = $id;
                        $res = $teacher->insertGetId($data);
                        if($res){
                            $tea=$users->where(array('tel'=>$_POST['tel']))->find();
                            return show(config('code.success'),'教师注册成功',$tea);
                        }else{
                            return show(config('code.error'),'教师注册失败');
                            //echo '<script>alert(\'同步教师信息失败！\');history.back(-1);</script>';
                        }
                    }else if(input('post.user_auth') == 3){
                        $student = Db::name('student');
                        $data['student_id'] = $id;
                        $data['student_rank_id'] = 1;
                        $res = $student->insertGetId($data);
                        if($res){
                            $coin = Db::name('coin');
                            $dat['receive_id'] = $id;
                            $coins = $coin->insertGetId($dat);
                            if($coins){
                                $stu=$users->where(array('tel'=>$_POST['tel']))->find();
                                return show(config('code.success'),'学生注册成功',$stu);
                            }else{
                                return show(config('code.error'),'学生注册失败');
                                //echo '<script>alert(\'同步学生学币信息失败！\');history.back(-1);</script>';
                            }
                        }else{
                            //echo '<script>alert(\'同步学生信息失败！\');history.back(-1);</script>';
                        }
                    }


                    //echo '<script>alert(\'添加成功！\');window.location.href=\''.U('Member/index').'\';</script>';
                } else {
                    return show(config('code.error'),'注册失败');
                    // echo '<script>alert(\'添加失败！\');history.back(-1);</script>';
                }

            }else{

                return show(config('code.error'),'该号码已注册');
            }
        }else{


        }
    }
    public function change_pass(){
        $status0['status']=0;
        $status1['status']=1;
        $status2['status']=2;
        $pass = md5($_POST['password']);
        $name = $_POST['username'];
        $users = Db::name('user');
        $data['password']=$pass;
        $info=$users->where("username='%s'OR tel='%s'",array($name,$name))->find();
        if($info['password']!=$pass) {
            if ($users->where("username='%s'OR tel='%s'", array($name, $name))->update($data)) {
                return json($status0);
                //echo '<script>alert(\'修改成功！\');window.location.href=\''.U('Member/index').'\';</script>';
            } else {
                return json($status1);
                //echo '<script>alert(\'修改失败！\');history.back(-1);</script>';
            }
        }else{
            return json($status2);
        }
    }

    public function edit_password(){

        $data = $_POST;
        if(empty($data)) {
            return show(config('code.error'), '数据不合法！', [], 404);
        }

        if(!isset($data['id'])){
            return show(config('code.error'), 'id is not found', [], 404);
        }

        $user_info = Db::name('user')
            ->where('id='.$data['id'])
            ->field('password')
            ->find();

        if(!empty($user_info['password'])){
            if(!isset($data['old_password'])){
                return show(config('code.error'), 'old_password is not found', [], 404);
            }
            $data['old_password'] = md5($data['old_password']);
        }

        if(!isset($data['password'])){
            return show(config('code.error'), 'password is not found', [], 404);
        }else{
            $change['password'] = md5($data['password']);
        }

        try{
            $users = Db::name('user');
            $info = $users
                ->where('id='.$data['id'])
                ->field('password')
                ->find();

            if(!empty($info['password'])){
                if($info['password'] == $data['old_password']) {
                    if($data['old_password'] == $change['password']){
                        return show(config('code.error'),'新密码与原始密码一致！');
                    }
                    if ($users
                        ->where('id='.$data['id'])
                        ->update($change)
                    ) {
                        return show(config('code.success'),'密码修改成功！',$change);
                    } else {
                        return show(config('code.error'), '密码修改失败！');
                    }
                }else{
                    return show(config('code.error'), '原始密码不正确！');
                }
            }elseif(empty($info['password'])){
                if ($users
                    ->where('id='.$data['id'])
                    ->update($change)
                ) {
                    return show(config('code.success'),'密码修改成功！',$change);
                } else {
                    return show(config('code.error'), '密码修改失败！');
                }
            }
        }catch (\Exception $e){
            Log::write($e->getMessage());
            return show(config('code.error'),$e->getMessage(),[],500);
        }

    }

//用户信息修改
    public function edit_user(){
        $status0['status']=0;
        $status1['status']=1;
        $id=$_POST['id'];
        $users =new User();
            if($users->where('id='.$id)->update($_POST)){
                return json($status0);
               // echo '<script>alert(\'修改成功！\');window.location.href=\''.U('Member/index').'\';</script>';
            }else{
                return json($status1);
                //echo '<script>alert(\'修改失败！\');history.back(-1);</script>';
            }

    }
//教师信息修改
    public function edit_teacher(){
        $status0['status']=0;
        $status1['status']=1;
        $id=$_POST['teacher_id'];
        $users = new Teacher();
            if($users->where('teacher_id='.$id)->update($_POST)){
                return json($status0);
                // echo '<script>alert(\'修改成功！\');window.location.href=\''.U('Member/index').'\';</script>';
            }else{
                return json($status1);
                //echo '<script>alert(\'修改失败！\');history.back(-1);</script>';
            }

    }
//学生信息修改
    public function edit_student()
    {
        $status0['status'] = 0;
        $status1['status'] = 1;
        $id = $_POST['student_id'];
        $users =new Student();
        if (request()->isPost()){
            if ($users->where('student_id=' . $id)->update($_POST)) {
                return json($status0);
                // echo '<script>alert(\'修改成功！\');window.location.href=\''.U('Member/index').'\';</script>';
            } else {
                return json($status1);
                //echo '<script>alert(\'修改失败！\');history.back(-1);</script>';
            }
    }
    }

    public function check_username(){
        $status0['status'] = 0;
        $status1['status'] = 1;
        $status2['status'] = 2;
        $user = Db::name('user');
        $id=$_POST['id'];
        $result = $user
            ->where('id='.$id)
            ->field('username')
            ->find();
        if(empty($result['username'])){
            $username = $_POST['username'];
            $res = $user
                ->field('username')
                ->select();
            $arr = [];
            foreach($res as $k => $v){
                $arr[$k] = $v['username'];
            }
            if(in_array($username,$arr)){
                return json($status1);
            }else{
                $data['username']=$_POST['username'];
                $user->where('id='.$id)->insert($data);
                if($user){
                    return json($status0);
                }else{
                    return json($status1);
                }

            }
        }else if(!empty($result)){
            return json($status2);
        }
    }

    public function check_tel(){
        $status0['status'] = 0;
        $status1['status'] = 1;
        $status2['status'] = 2;
        $user = Db::name('user');
        $id=$_POST['id'];
        $tel = $_POST['tel'];
            $res = $user->field('tel')->select();
        $arr = [];
        foreach($res as $k => $v) {
            $arr[$k] = $v['tel'];
        }
            if(in_array($tel,$arr)){
                return json($status1);
            }else{
                $data['tel']=$_POST['tel'];
                $user->where('id='.$id)->insert($data);
                if($user){
                    return json($status0);
                }else{
                    return json($status1);
                }

            }
        }

}